/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wels.sample;

import com.wels.sample.slice.MainAbilitySlice;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.bundle.IBundleManager;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * MainAbility Class
 */
public class MainAbility extends Ability {
    private static final HiLogLabel TAG = new HiLogLabel(3, 0xD000F00, MainAbility.class.getSimpleName());

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());

        if (verifySelfPermission("ohos.permission.READ_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED ||
                verifySelfPermission("ohos.permission.WRITE_USER_STORAGE") != IBundleManager.PERMISSION_GRANTED) {
            requestPermissionsFromUser(
                    new String[]{
                            "ohos.permission.READ_USER_STORAGE",
                            "ohos.permission.WRITE_USER_STORAGE"
                    }, 12);
        }
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 12 && grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
            HiLog.info(TAG, "permission granted");
            Context context = getContext();
            createFileEntriesForAutoEncoding(context);
            createFileEntriesForManualEncoding(context);
            createFileEntriesForManualDecoding(context);
            createFileEntriesForAutoDecoding(context);
        }
    }

    private void createFileEntriesForManualDecoding(Context context) {
        String devicePath = getContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/manual_decode";
        File myDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath(), "manual_decode");
        if (myDir.mkdir()) {
            HiLog.info(TAG, "createFileEntriesForManualDecoding mkdir successful");
        }
        String localFilePath = "resources/rawfile/decoding/";
        String[] filesNames = {"decode_input.yuv.264", "BitStreams.txt"};

        for (int index = 0; index < filesNames.length; index++) {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(localFilePath + filesNames[index]);
            if (rawFileEntry != null) {
                try {
                    Resource resource = rawFileEntry.openRawFile();
                    File file = new File(devicePath + File.separator + filesNames[index]);
                    createFile(resource, file);
                } catch (IOException ioException) {
                    HiLog.error(TAG, ioException.getMessage());
                }
            }
        }
    }

    private void createFile(Resource resource, File file) {
        if (!file.exists()) {
            try (FileOutputStream fos = new FileOutputStream(file);) {
                byte[] byteObj = new byte[1024];
                int length = 0;
                while ((length = resource.read(byteObj)) != -1) {
                    fos.write(byteObj, 0, length);
                }
            } catch (IOException e) {
                HiLog.error(TAG, e.getMessage());
            }
        }
    }

    private void createFileEntriesForAutoDecoding(Context context) {
        String devicePath = getContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/auto_decode";
        File myDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath(), "auto_decode");
        if (myDir.mkdir()) {
            HiLog.info(TAG, "createFileEntriesForAutoDecoding mkdir successful");
        }
        String localFilePath = "resources/rawfile/decoding/";
        String filesName = "decode_input.yuv.264";

        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(localFilePath + filesName);
        if (rawFileEntry != null) {
            try {
                Resource resource = rawFileEntry.openRawFile();
                File file = new File(devicePath + File.separator + filesName);
                createFile(resource, file);
            } catch (IOException e) {
                HiLog.error(TAG, e.getMessage());
            }
        }
    }

    private void createFileEntriesForAutoEncoding(Context context) {
        String devicePath = getContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/auto_encode";
        File myDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath(), "auto_encode");
        if (myDir.mkdir()) {
            HiLog.info(TAG, "createFileEntriesForManualEncoding mkdir successful");
        }
        String localFilePath = "resources/rawfile/auto_encoding/";
        String[] filesNames = {"Cisco_Absolute_Power_1280x720_30fps.yuv", "layer2.cfg", "welsenc.cfg"};

        createFiles(context, filesNames, localFilePath, devicePath);
    }

    private void createFileEntriesForManualEncoding(Context context) {
        String devicePath = getContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) + "/manual_encode";
        File myDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath(), "manual_encode");
        if (myDir.mkdir()) {
            HiLog.info(TAG, "createFileEntriesForManualEncoding mkdir successful");
        }
        String localFilePath = "resources/rawfile/manual_encoding/";
        String[] filesNames = {"cfgs.txt", "layer2.cfg", "layer2_arbitrary_res.cfg", "Static_152_100.yuv",
                "welsenc.cfg", "welsenc_arbitrary_res.cfg"};

        createFiles(context, filesNames, localFilePath, devicePath);
    }

    private void createFiles(Context context, String[] filesNames, String localFilePath, String devicePath) {
        for (int index = 0; index < filesNames.length; index++) {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(localFilePath + filesNames[index]);
            if (rawFileEntry != null) {
                try {
                    Resource resource = rawFileEntry.openRawFile();
                    File file = new File(devicePath + File.separator + filesNames[index]);
                    createFile(resource, file);
                } catch (IOException e) {
                    HiLog.error(TAG, e.getMessage());
                }
            }
        }
    }
}